<template>
  <div class="page-main">
    <query-page
      ref="queryPageRef"
      v-model:selectedKeys="selectedKeys"
      :form-component-config="formComponentConfig"
      :form-render-config="formRenderConfig"
      :form-render-keys="formRenderKeys"
      :table-component-config="tableComponentConfig"
      :table-render-config="tableRenderConfig"
      :table-render-keys="tableRenderKeys"
      :loading="isLoading"
      :data="renderData"
      :total="total"
      row-key="id"
      :has-line="false"
      title="采购计划编制"
      row-selection-type="checkbox"
      @selection-change="selectionChange"
      @query-data="getData"
    >
      <template #top-container>
        <p-tabs
          v-model:value="activeTab"
          :is-show-num="false"
          :tab-list="materialType"
          @change="handleChange"
        ></p-tabs>
      </template>
      <!-- 制单状态（0-编制中，1-待审批，2-审批中，3-审批通过，4 -拒绝 5-商务经理接收） -->
      <template #businessStatusName="{ record }">
        <div
          :class="{
            red: record.businessStatus === 4,
            green: record.businessStatus === 3,
            yellow: [0, 1, 2, 5].includes(record.businessStatus),
          }"
        >
          <span class="dot"></span>
          {{ record.businessStatusName }}
        </div>
      </template>
      <template #container-side>
        <a-space>
          <a-button
            v-permission="['procurement:plan-list:updateDataOrNotes']"
            :disabled="!selectedKeys.length"
            @click="batchAdjustPlan"
            >批量调整计划到货日期</a-button
          >
          <a-button
            v-permission="['procurement:plan-list:updateDataOrNotes']"
            :disabled="!selectedKeys.length"
            @click="batchAdjustRemark"
            >批量调整备注</a-button
          >
          <a-button
            v-permission="['procurement:plan-list:editFinishOrAgain']"
            :disabled="!selectedKeys.length"
            @click="authorizedAccomplish"
            >编制完成</a-button
          >
          <a-button
            v-permission="['procurement:plan-list:editFinishOrAgain']"
            :disabled="!selectedKeys.length"
            @click="anewAuthorized"
            >重新编制</a-button
          >
          <a-button
            v-permission="['procurement:plan-list:submitForApproval']"
            :disabled="!selectedKeys.length"
            @click="SubmitExamine"
            >提交审批</a-button
          >
          <div v-permission="['procurement:plan-list:importForEdit']">
            <batchImport
              title="采购计划编制"
              btn-tititle="Excel导入"
              export-type="apiUrl"
              file-code="require_planJBHZDRUrl"
              import-url="/api/procurement/require/plan-list/importForEdit"
              @finish="getData"
            ></batchImport>
          </div>
        </a-space>
        <a-modal
          v-model:visible="batchAdjustPlanFlag"
          :on-before-ok="handleOkBatchAdjustPlan"
          width="480px"
          @cancel="handleCancel"
        >
          <template #title> 指定计划到货日期 </template>
          <a-form
            ref="formRefTime"
            :model="showForm"
            :rules="rules"
            auto-label-width
            layout="horizontal"
          >
            <a-form-item
              field="selectedDate"
              label="计划到货日期"
              validate-trigger="blur"
            >
              <a-date-picker
                v-model="showForm.selectedDate"
                format="YYYY-MM-DD"
                @change="onChange"
              />
            </a-form-item>
          </a-form>
        </a-modal>
        <a-modal
          v-model:visible="batchAdjustRemarkFlag"
          :on-before-ok="handleOkBatchAdjustRemark"
          width="480px"
          @cancel="handleCancel"
        >
          <template #title> 指定备注 </template>
          <a-form
            ref="formRef"
            :model="showForm"
            :rules="rules"
            auto-label-width
          >
            <a-form-item
              field="textContent"
              label="备注"
              validate-trigger="blur"
            >
              <a-space direction="vertical" size="large" fill>
                <a-textarea
                  v-model="showForm.textContent"
                  style="width: 340px"
                  placeholder="请输入备注信息,最大输入1000字符"
                  :max-length="1000"
                  allow-clear
                  show-word-limit
                />
              </a-space>
            </a-form-item>
          </a-form>
        </a-modal>
      </template>
      <!-- 1.调整计划到货日期   编制中和审核拒绝的
   2.调整备注           编制中和审核拒绝的
   3.编制完成           编制中 编制完成  审核拒绝的
   4.重新编制           编制中 编制完成  审核拒绝的
   5.提交审批           编制完成 -->
      <!-- 制单状态（0-编制中，1-待审批，2-审批中，3-审批通过，4 -拒绝 5-商务经理接收） -->
      <template #operate="{ record }">
        <a-button
          v-permission="['procurement:plan-list:updatePlan']"
          :hidden="[1, 5].includes(record.businessStatus)"
          type="text"
          @click="compile(record)"
        >
          编辑
        </a-button>
        <a-button
          v-permission="['procurement:plan-list:updateDataOrNotes']"
          :hidden="[1, 2, 3, 5].includes(record.businessStatus)"
          type="text"
          @click="batchAdjustPlan(record)"
          >调整计划到货日期</a-button
        >
        <a-button
          v-permission="['procurement:plan-list:updateDataOrNotes']"
          :hidden="[1, 2, 3, 5].includes(record.businessStatus)"
          type="text"
          @click="batchAdjustRemark(record)"
          >调整备注</a-button
        >
        <a-button
          v-permission="['procurement:plan-list:editFinishOrAgain']"
          :hidden="[2, 5].includes(record.businessStatus)"
          type="text"
          @click="authorizedAccomplish(record)"
          >编制完成</a-button
        >
        <a-button
          v-permission="['procurement:plan-list:editFinishOrAgain']"
          :hidden="[2, 5].includes(record.businessStatus)"
          type="text"
          @click="anewAuthorized(record)"
          >重新编制</a-button
        >
        <a-button
          v-permission="['procurement:plan-list:submitForApproval']"
          :hidden="[0, 5].includes(record.businessStatus)"
          type="text"
          @click="SubmitExamine(record)"
          >提交审批</a-button
        >
      </template>
    </query-page>

    <a-modal
      :visible="editVisible"
      title="编辑"
      @cancel="handleCancels"
      @ok="handleOk"
    >
      <a-form ref="formRefs" :model="editForm">
        <a-form-item field="planQty" label="订货数量">
          <a-input v-model="editForm.planQty" />
        </a-form-item>
        <a-form-item field="planArrivalDate" label="计划到货日期">
          <a-date-picker
            v-model="editForm.planArrivalDate"
            style="width: 100%"
            format="YYYY-MM-DD"
            placeholder="请选择"
          />
        </a-form-item>
        <a-form-item field="purchaseState" label="是否采购">
          <a-select v-model="editForm.purchaseState" placeholder="请确认">
            <a-option :value="1">是</a-option>
            <a-option :value="0">否</a-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>
    <!-- 提交审批 -->
    <!-- <planAlterationReceiveSubmitExamine
      v-if="showModal"
    ></planAlterationReceiveSubmitExamine> -->
  </div>
</template>

<script lang="ts" setup>
  import { ref, onMounted, nextTick } from 'vue';
  import { Message } from '@arco-design/web-vue';
  import queryPage from '@/common/components/query-page/index.vue';
  import {
    formRenderConfig,
    formComponentConfig,
  } from '@/views/purchase-plan/components/formComp/baseFormConfig';
  import {
    tableRenderConfig,
    tableComponentConfig,
  } from '@/views/purchase-plan/components/tableComp/baseTableConfig';
  import { baseRenderKeys } from '@/views/purchase-plan/components/baseData';
  // import dictSelect from '@/common/components/dict-select/index.vue';

  // import useModal from '@/common/hooks/modal';
  // import { warning } from '@/common/utils/modal-promise';
  // editFinishOrAgain
  import modalPromise from '@/common/utils/modal-promise';

  import {
    getPlanListPage,
    updateDataOrNotes,
    editFinishOrAgain,
    submitForApproval,
    updatePlan,
  } from '@/api/purchase-plan/planAuthorized';
  // import planAlterationReceiveSubmitExamine from '@/views/purchase-plan/plan-alteration-receive-submitExamine/index.vue';
  // import PageTitle from '@/common/components/title/page-title.vue';
  import { materialType } from '@/config/const';
  import batchImport from '@/common/components/batch-import/index.vue';
  import PTabs from '../components/p-tabs.vue';

  // 物料类型代码( 1标准件 2 成品 3原材料 4 零组件 5锻铸件)

  const queryPageRef = ref();
  // tab 头部切换change
  const handleChange = async (val) => {
    activeTab.value = val;
    console.log(val, 'tab 头部切换change');
    selectedKeys.value = [];
    initData();
    await nextTick(() => {
      queryPageRef.value.setCurrent(1);
      getData();
    });
  };
  const editForm = ref({
    planQty: '',
    planArrivalDate: '',
    purchaseState: '',
  });

  const editVisible = ref(false);

  const handleCancels = () => {
    editVisible.value = false;
  };
  const formRefs = ref();
  const handleOk = () => {
    formRefs.value.validate(async (validate) => {
      if (!validate) {
        const params = {
          ...editForm.value,
          id: selectObj.value.id,
        };

        try {
          const res = (await updatePlan(params)) as any;
          if (res.code === 200) {
            getData();
            Message.success({
              content: '修改成功!',
            });
          }
        } catch (err: any) {
          console.log(err);
        } finally {
          isLoading.value = false;
        }
        editVisible.value = false;
      }
    });
  };

  const selectedKeys = ref([]);
  const activeTab = ref('2');
  const isLoading = ref(true);
  const renderData = ref<any[]>([]);
  const total = ref(0);
  const selection = ref<any[]>([]);
  const showForm = ref({
    textContent: '',
    selectedDate: '',
  });
  const formRef = ref();
  const formRefTime = ref();
  const selectedDate = ref(null);
  // 渲染检索项
  const formRenderKeys = ref<any[]>([]);
  // 当前表格要渲染哪些值
  const tableRenderKeys = ref<any[]>([]);
  // 传递给后台的字段
  const deliveryInfo = ref({
    form: {},
  });
  const rules = ref({
    textContent: [{ required: true, message: '备注必输' }],
    selectedDate: [{ required: true, message: '计划到货日期必输' }],
  });
  const selectObj = ref();

  //  表头数据
  interface Tst {
    [index: string]: any;
  }
  // 物料类型代码( 1标准件 2 成品 3原材料 4 零组件 5锻铸件)
  const dataRenderBase = ref<Tst>({
    '2': baseRenderKeys.finishedProduct.formRenderKeys,
    '3': baseRenderKeys.rawMaterial.formRenderKeys,
    '1': baseRenderKeys.standardPart.formRenderKeys,
    '4': baseRenderKeys.zeroCom.formRenderKeys,
    '5': baseRenderKeys.forgingAndCasting.formRenderKeys,
  });
  // 表格数据
  const dataRenderBase2 = ref<Tst>({
    '2': baseRenderKeys.finishedProduct.newTableRenderKeys,
    '3': baseRenderKeys.rawMaterial.newTableRenderKeys,
    '1': baseRenderKeys.standardPart.newTableRenderKeys,
    '4': baseRenderKeys.zeroCom.newTableRenderKeys,
    '5': baseRenderKeys.forgingAndCasting.newTableRenderKeys,
  });
  console.log(dataRenderBase2, 'dataRenderBase2');

  // 获取筛选form的renderKey(表单渲染项)
  formRenderKeys.value = dataRenderBase.value[activeTab.value];
  console.log(formRenderKeys.value, 'formRenderKeys.value');
  tableRenderKeys.value = dataRenderBase2.value[activeTab.value];
  console.log(tableRenderKeys.value, ' tableRenderKeys.value');

  // 表单选中的数据
  // let selectList = reactive<string[]>([]);

  // const selectionChange = (val: string[]) => {
  //   selectList = val;
  //   console.log('selectedKeys11111', val);
  // };
  const selectionChange = (val: string[]) => {
    console.log(val, 'valvalvalval');
    // selectList = val;
    selection.value = renderData.value.filter((item) => {
      console.log(item, 'item++++++++++++');
      return val.includes(item.id);
    });

    console.log(selection, 'selectionselectionselection');
  };
  // 初始化列表
  const getData = async (queryInfo: object) => {
    if (!queryInfo) {
      queryInfo = queryPageRef.value.getStatus();
    }
    renderData.value = [];
    isLoading.value = true;
    console.log('queryInfo', queryInfo);
    deliveryInfo.value.form = { ...queryInfo };

    // 物料类型代码( 1标准件 2 成品 3原材料 4 零组件 5锻铸件)
    try {
      const res = (await getPlanListPage({
        mdsItemType: activeTab.value,
        ...queryInfo,
      })) as any;
      console.log(res, 'res+++++++++++++');
      if (res.code === 200) {
        total.value = res.data.total;
        renderData.value = res.data.list;
      }
    } finally {
      isLoading.value = false;
    }
  };
  // 初期话
  const initData = () => {
    console.log('-----------------------------');
    // 获取筛选form的renderKey(表单渲染项)
    formRenderKeys.value = dataRenderBase.value[activeTab.value];
    tableRenderKeys.value = [...dataRenderBase2.value[activeTab.value]];
  };
  // 批量调整计划到货日期
  const batchAdjustPlanFlag = ref(false);
  const batchAdjustPlan = (record: any) => {
    showForm.value.selectedDate = '';
    selectObj.value = record;
    showForm.value.planArrivalDate = record.planArrivalDate;
    batchAdjustPlanFlag.value = true;
  };

  const onChange = (value: any) => {
    showForm.value.selectedDate = value;
    console.log(selectedDate, 'selectedDate');
  };

  const handleOkBatchAdjustPlan = async () => {
    // 更改计划到货日期  传参 id planArrivalDate(计划到货日期，格式“yyyy-MM-dd”)
    const verifyStatus = await formRefTime.value?.validate();
    let result = false;
    if (!verifyStatus) {
      result = true;
      let params = [];

      if (selectObj.value.id) {
        params = [
          {
            id: selectObj.value.id,
            planArrivalDate: showForm.value.selectedDate,
          },
        ];
      } else {
        selectedKeys.value.forEach((v) => {
          const obj = {
            id: v,
            planArrivalDate: showForm.value.selectedDate,
          };
          params.push(obj);
        });
      }
      try {
        const res = (await updateDataOrNotes(params)) as any;
        if (res.code === 200) {
          getData();
          Message.success({
            content: '指定计划到货日期成功!',
          });
        }
      } catch {
        return result;
      } finally {
        isLoading.value = false;
      }
    }
    return result;
  };
  // 批量调整备注
  const batchAdjustRemarkFlag = ref(false);
  const batchAdjustRemark = (record: any) => {
    showForm.value.textContent = '';
    selectObj.value = record;
    showForm.value.textContent = record.notes;
    batchAdjustRemarkFlag.value = true;
  };

  const handleOkBatchAdjustRemark = async () => {
    // ②更改备注  传参 id notes（备注）

    const verifyStatus = await formRef.value?.validate();
    let result = false;
    if (!verifyStatus) {
      result = true;
      let params = [];
      if (selectObj.value.id) {
        params = [
          {
            id: selectObj.value.id,
            notes: showForm.value.textContent,
          },
        ];
      } else {
        selectedKeys.value.forEach((v) => {
          const obj = {
            id: v,
            notes: showForm.value.textContent,
          };
          params.push(obj);
        });
      }
      try {
        const res = (await updateDataOrNotes(params)) as any;
        if (res.code === 200) {
          getData();
          Message.success({
            content: '批量调整备注成功!',
          });
          showForm.value.textContent = '';
        }
      } catch {
        return result;
      } finally {
        isLoading.value = false;
      }
    }
    return result;
  };
  const handleCancel = () => {
    showForm.value.textContent = '';
    showForm.value.selectedDate = '';
  };
  //
  // 编制完成 editFinishOrAgain
  const authorizedAccomplish = async (record: any) => {
    try {
      await modalPromise.info({
        title: '提示',
        content: '您确定要编制完成当前所选的数据？',
        hideCancel: false,
      });
    } catch {
      return;
    }
    await authorizedAccomplishDialogs(record);
  };
  const authorizedAccomplishDialogs = async (record: any) => {
    let params = [];
    if (record.id) {
      params = [
        {
          id: record.id,
          businessStatus: 1,
        },
      ];
    } else {
      selectedKeys.value.forEach((v) => {
        const obj = {
          id: v,
          businessStatus: 1,
        };
        params.push(obj);
      });
    }

    try {
      const res = (await editFinishOrAgain(params)) as any;
      if (res.code === 200) {
        getData();
        Message.success({
          content: '编制成功!',
        });
      }
    } finally {
      isLoading.value = false;
    }
  };
  // 重新编制
  const anewAuthorized = async (record: any) => {
    try {
      await modalPromise.info({
        title: '提示',
        content: '您确定要重新编制当前所选的数据？',
        hideCancel: false,
      });
    } catch {
      return;
    }
    await anewAuthorizedDialogs(record);
  };
  const anewAuthorizedDialogs = async (record: any) => {
    // ②重新编制  传参id， businessStatus=0
    let params = [];
    if (record.id) {
      params = [
        {
          id: record.id,
          businessStatus: 0,
        },
      ];
    } else {
      selectedKeys.value.forEach((v) => {
        const obj = {
          id: v,
          businessStatus: 0,
        };
        params.push(obj);
      });
    }
    try {
      const res = (await editFinishOrAgain(params)) as any;
      if (res.code === 200) {
        getData();
        Message.success({
          content: '编制成功!',
        });
      }
    } finally {
      isLoading.value = false;
    }
  };
  // 添加弹框的事件
  // const { showModal, openModal } = useModal();
  // 提交审批
  const SubmitExamine = async (record: any) => {
    try {
      await modalPromise.info({
        title: '提示',
        content: '您确定要提交审批当前所选的数据？',
        hideCancel: false,
      });
    } catch {
      return;
    }
    await SubmitExamineDialogs(record);
  };

  const SubmitExamineDialogs = async (record: any) => {
    // 提交审批  传惨 id businessStatus =5
    let params = [];
    if (record.id) {
      params = [
        {
          id: record.id,
          businessStatus: 5,
        },
      ];
    } else {
      selectedKeys.value.forEach((v) => {
        const obj = {
          id: v,
          businessStatus: 5,
        };
        params.push(obj);
      });
    }
    try {
      const res = (await submitForApproval(params)) as any;
      if (res.code === 200) {
        getData();
        Message.success({
          content: '提交审批!',
        });
      }
    } finally {
      isLoading.value = false;
    }
  };
  // 编辑
  const compile = async (rowDate: any) => {
    editVisible.value = true;
    selectObj.value = rowDate;
    editForm.value = {
      planQty: rowDate.planQty,
      planArrivalDate: rowDate.planArrivalDate,
      purchaseState: rowDate.purchaseState,
    };
  };

  onMounted(() => {
    initData();
  });
</script>

<style lang="less" scoped>
  .dot {
    display: inline-block;
    width: 6px;
    height: 6px;
    margin-right: 2px;
    border-radius: 4px;
  }

  .red {
    color: #d40000;
    .dot {
      background-color: #d40000;
    }
  }

  .green {
    color: #2ca340;
    .dot {
      background-color: #2ca340;
    }
  }

  .yellow {
    color: #c78b00;
    .dot {
      background-color: #c78b00;
    }
  }
</style>
